本文主要介绍spring boot如何使用JDBCTemplate来访问Mysql,对单表做简单的增删改查操作。
环境说明:
IntelliJ IDEA
JDK 1.8
spring boot 2.1.0
Maven 3.5.0
Mysql
一、初始化mysql 创建数据库,创建数据表,并生成一些测试数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 CREATE DATABASE spring_boot_study;USE spring_boot_study;DROP TABLE IF EXISTS `user_manage` ;CREATE TABLE `user_manage` ( `id` int (11 ) NOT NULL AUTO_INCREMENT, `user_name` varchar (20 ) NOT NULL , `password` varchar (20 ) NOT NULL , `telPhone` varchar (20 ) NOT NULL , `cdate` datetime DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`id` ) ) ENGINE =InnoDB DEFAULT CHARSET =utf8; INSERT INTO `user_manage` VALUES ('1' , 'admin' , '12345678' , '1761581****' , '2017-09-11 15:03:49' );INSERT INTO `user_manage` VALUES ('2' , 'tom' , '12345678' , '178********' , '2017-09-17 10:19:06' );INSERT INTO `user_manage` VALUES ('3' , 'seven' , 'admin111' , '176********' , '2017-10-27 20:33:40' );INSERT INTO `user_manage` VALUES ('4' , 'Mary' , '11111111' , '1786281****' , '2017-12-12 16:33:53' );
二、spring boot配置 1. application.yml 根据个人喜好选择配置文件的类型,在这里我选择配置application.yml,主要对datasource进行一些配置说明。
1 2 3 4 5 6 7 8 9 10 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring_boot_study?allowMultiQueries=true&serverTimezone=GMT%2B8 username: root password: root server: port: 8081 servlet: context-path: /spring-boot-study
2. pom.xml 至少引入下面三个依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-jdbc</artifactId > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <scope > runtime</scope > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency >
三、具体编码 我们如果要制作API接口的话,需要编写四个层:实体(Entity)层;DAO层;Service层;Controller层。
1. 实体(Entity)层: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 public class UsersEntity { private int id; private String userName; private String password; private String telPhone; private String cdate; public int getId () { return id; } public void setId (int id) { this .id = id; } public String getUserName () { return userName; } public void setUserName (String userName) { this .userName = userName; } public String getPassword () { return password; } public void setPassword (String password) { this .password = password; } public String getTelPhone () { return telPhone; } public void setTelPhone (String telPhone) { this .telPhone = telPhone; } public String getCdate () { return cdate; } public void setCdate (String cdate) { this .cdate = cdate; } @Override public String toString () { return "UsersEntity{" + "id=" + id + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", telPhone='" + telPhone + '\'' + ", cdate='" + cdate + '\'' + '}' ; } }
2. DAO层 由接口和实现类组成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public interface UsersDAO { List<UsersEntity> usersList () ; UsersEntity findUserOne (String name) ; void saveUser (UsersEntity usersEntity) ; void updateUser (UsersEntity usersEntity) ; void removeUser (String name) ; }
实现类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 @Repository public class UsersDaoImpl implements UsersDAO { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<UsersEntity> usersList () { List<UsersEntity> list = jdbcTemplate.query("select * from user_manage" , new Object[]{}, new BeanPropertyRowMapper(UsersEntity.class)); return list; } @Override public UsersEntity findUserOne (String name) { List<UsersEntity> list = jdbcTemplate.query("select * from user_manage where user_name = ?" , new Object[]{name}, new BeanPropertyRowMapper(UsersEntity.class)); if (list != null && list.size() > 0 ) { UsersEntity usersEntity = list.get(0 ); return usersEntity; } else { return null ; } } @Override public void saveUser (UsersEntity usersEntity) { jdbcTemplate.update("insert into user_manage(user_name, password, telPhone) values(?, ?, ?)" , usersEntity.getUserName(), usersEntity.getPassword(), usersEntity.getTelPhone()); } @Override public void updateUser (UsersEntity usersEntity) { jdbcTemplate.update("UPDATE user_manage SET password=?, telPhone=? WHERE user_name=?" , usersEntity.getPassword(), usersEntity.getTelPhone(), usersEntity.getUserName()); } @Override public void removeUser (String name) { jdbcTemplate.update("DELETE FROM user_manage WHERE user_name = ?" , name); } }
说明:
需要在DAO层的实现类里面加入注解@Repository
通过注解@Autowired来引用JdbcTemplate
3. Service层 由接口与实现类组成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public interface UsersService { List<UsersEntity> usersList () ; UsersEntity findUserOne (String name) ; void saveUser (UsersEntity usersEntity) ; void updateUser (UsersEntity usersEntity) ; void removeUser (String name) ; }
实现类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 @Service public class UsersServiceImpl implements UsersService { @Autowired private UsersDAO usersDao; @Override public List<UsersEntity> usersList () { return usersDao.usersList(); } @Override public UsersEntity findUserOne (String name) { return usersDao.findUserOne(name); } @Override public void saveUser (UsersEntity usersEntity) { usersDao.saveUser(usersEntity); } @Override public void updateUser (UsersEntity usersEntity) { usersDao.updateUser(usersEntity); } @Override public void removeUser (String name) { usersDao.removeUser(name); } }
说明:
需要在Serivice层的实现类里面加入注解@Service
通过注解@Autowired来引用DAO层的接口UsersDAO
4. Controller层 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 @RestController @RequestMapping ("users" )public class UsersController { @Autowired private UsersService usersService; @RequestMapping (value = "list" , method = RequestMethod.GET) public List<UsersEntity> list () { return usersService.usersList(); } @RequestMapping (value = "{name}" , method = RequestMethod.GET) public UsersEntity findUserOne (@PathVariable("name" ) String name) { return usersService.findUserOne(name); } @RequestMapping (value = "save" , method = RequestMethod.POST) public Map<String,Boolean> save (UsersEntity usersEntity) { Map<String,Boolean> map = new HashMap<>(); try { usersService.saveUser(usersEntity); map.put("status" ,true ); } catch (Exception e) { map.put("status" ,false ); } return map; } @RequestMapping (value = "update" , method = RequestMethod.PUT) public Map<String,Boolean> update (UsersEntity usersEntity) { Map<String,Boolean> map = new HashMap<>(); try { usersService.updateUser(usersEntity); map.put("status" ,true ); } catch (Exception e) { map.put("status" ,false ); } return map; } @RequestMapping (value = "remove" , method = RequestMethod.DELETE) public Map<String,Boolean> remove (@RequestParam(value = "userName" ,required = true ) String name) { Map<String,Boolean> map = new HashMap<>(); try { usersService.removeUser(name); map.put("status" ,true ); } catch (Exception e) { e.printStackTrace(); map.put("status" ,false ); } return map; } }
说明:
需要在Controller层的类里面加入注解@RestController与@RequestMapping(“xxx”)
通过注解@Autowired来引用Service层的接口UsersService
四、功能测试 通过Jrebel v2018.2.2
来启动spring boot
程序,可以实现热部署(代码修改即时生效)。
查询所有
浏览器访问:http://localhost:8081/spring-boot-study/users/list,如下图所示:
条件查询:根据name查询单条信息
浏览器访问:http://localhost:8081/spring-boot-study/users/tom,如下图所示:
这里我们使用Postman工具,来测试增加、更新、删除信息。
增加一条信息
更新一条信息:
删除一条信息
五、注解概述 1. @RestController Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。 即@RestController是@ResponseBody和@Controller的组合注解。
2. @RequestMapping :配置url映射 3. @PathVariable:url参数化 当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。具体可见上述实例的删除代码逻辑。
4. @Autowired 这是一个非常常见的注解。 比如在上述代码示例中所示:在Controller层,需要使用@Autowired来调用Service层;在Service层,需要使用@Autowired来调用DAO层;在DAO层实现类中,通过@Autowired来调用JdbcTemplate。
5. @Repository:用于标注数据访问组件,即DAO组件。标注在实现类上。 6. @Service注解:用于标注Service层组件,标注在实现类上。 7. @Controller注解:用于标注Controller层组件。 六、总结 前面说了那么多,用几句话来概括一下:
首先需要创建数据库,数据表
修改yml配置文件,配置datasource
在pom文件中引入相关依赖
具体编码。通过JdbcTemplate来操作Mysql,编写Entity、DAO、Service、Controller。
会使用基础注解
在以后,我会抽出时间来学习并分享spring boot的基本用法。除了大数据服务组件之外,现在非常火爆的spring boot框架也不能落下,一起学习吧。
源码已上传至https://github.com/841809077/spring-boot-study